package com.merlin.gateway;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;

import com.alibaba.fastjson.JSONObject;

/**
 * 
* @ClassName:：FallbackProvider 
* @Description：统一配置路由的fallback
* @author ：张海滨(merlin)
* @date ：2020年1月11日 下午1:04:42 
*
 */
@Configuration
public class FallbackProvider
{

	private final Logger logger = LoggerFactory.getLogger(FallbackProvider.class);

	@Bean
	public ZuulFallbackProvider emrFallbackProvider()
	{
		return getFallbackProvider("tkh-emr-app");
	}


	/**
	 * 根据serverId生成对应的FallbackProvider
	 * @param serverId  
	 * @return
	 */
	public ZuulFallbackProvider getFallbackProvider(String serverId)
	{

		logger.info(serverId + " 服务调用目标服务时发生错误！");
		return new ZuulFallbackProvider() {

			@Override
			public String getRoute()
			{
				return serverId;
			}

			@Override
			public ClientHttpResponse fallbackResponse()
			{
				return new ClientHttpResponse() {
					@Override
					public InputStream getBody() throws IOException
					{
						JSONObject json = new JSONObject();
						json.put("code", "2");
						json.put("msg", "ApiGateway调用目标服务时发生错误！");
						return new ByteArrayInputStream(json.toJSONString().getBytes("utf-8"));
					}

					@Override
					public HttpHeaders getHeaders()
					{
						HttpHeaders headers = new HttpHeaders();
						headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
						return headers;
					}

					@Override
					public HttpStatus getStatusCode() throws IOException
					{
						return HttpStatus.OK;
					}

					@Override
					public int getRawStatusCode() throws IOException
					{
						return 200;
					}

					@Override
					public String getStatusText() throws IOException
					{
						return "OK";
					}

					@Override
					public void close()
					{
					}
				};
			}
		};
	}

}
